package org.jeecg.modules.cusorder.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.cusorder.entity.CusOrderInfo;
import org.jeecg.modules.cusorder.mapper.CusOrderInfoMapper;
import org.jeecg.modules.cusorder.service.ICusOrderInfoService;
import org.jeecg.modules.cusstyle.entity.CusStyleInfo;
import org.jeecg.modules.cusstyle.service.ICusStyleInfoService;
import org.jeecg.modules.manage.entity.StyleInfo;
import org.jeecg.modules.manage.entity.SysConfig;
import org.jeecg.modules.manage.service.IStyleInfoService;
import org.jeecg.modules.manage.service.ISysConfigService;
import org.jeecg.modules.system.controller.SysAnnouncementController;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.workorder.entity.WorkingOrder;
import org.jeecg.modules.workorder.entity.WorkingOrderRecord;
import org.jeecg.modules.workorder.service.IWorkingOrderRecordService;
import org.jeecg.modules.workorder.service.IWorkingOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 客户订单信息
 * @Date:   2021-09-10
 * @Version: V1.0
 */
@Api(tags="客户订单信息")
@RestController
@RequestMapping("/cusOrderInfo")
@Slf4j
public class CusOrderInfoController extends JeecgController<CusOrderInfo, ICusOrderInfoService> {
	
	@Autowired
	private ICusOrderInfoService cusOrderInfoService;
	
	@Autowired
	private IStyleInfoService styleInfoService;
	
	@Autowired
	private ICusStyleInfoService cusStyleInfoService;
	
	@Autowired
	private CusOrderInfoMapper cusOrderInfoMapper;
	
	@Autowired
    private ISysDictService sysDictService;
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
    private ISysConfigService sysConfigService;
	
	@Autowired
    private IWorkingOrderService workingOrderService;
	
	@Autowired
	private IWorkingOrderRecordService workingOrderRecordService;
	
	/**
	 * 订单管理-分页列表查询
	 *
	 * @param orderInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "订单信息-分页列表查询")
	@ApiOperation(value="订单信息-分页列表查询", notes="订单信息-分页列表查询")
	@GetMapping(value = "/olist")
	@PermissionData(pageComponent="cusOrder/CusOrderInfoList")
	public Result<?> queryOrderPageList(CusOrderInfo cusOrderInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CusOrderInfo> queryWrapper = QueryGenerator.initQueryWrapper(cusOrderInfo, req.getParameterMap());
		Page<CusOrderInfo> page = new Page<CusOrderInfo>(pageNo, pageSize);
		IPage<CusOrderInfo> pageList = cusOrderInfoService.page(page, queryWrapper);
		List<CusOrderInfo> list = pageList.getRecords();
		for(CusOrderInfo orderInfo : list) {
			String orderInfoId = orderInfo.getId();
			List<CusStyleInfo> styleList = this.cusOrderInfoService.getCusStyleInfoListByOrderId(orderInfoId);
			if(styleList == null || styleList.size() == 0) {
				orderInfo.setHasSelStyle(false);
			} else {
				orderInfo.setHasSelStyle(true);
			}
		}
		return Result.OK(pageList);
	}
	
	/**
	 * 开工单-分页列表查询
	 *
	 * @param orderInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "开工单-分页列表查询")
	@ApiOperation(value="开工单-分页列表查询", notes="开工单-分页列表查询")
	@GetMapping(value = "/plist")
	@PermissionData(pageComponent="cusOrder/ProdOrderInfoList")
	public Result<?> queryProdPageList(CusOrderInfo cusOrderInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CusOrderInfo> queryWrapper = QueryGenerator.initQueryWrapper(cusOrderInfo, req.getParameterMap());
		Page<CusOrderInfo> page = new Page<CusOrderInfo>(pageNo, pageSize);
		IPage<CusOrderInfo> pageList = cusOrderInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 * 成品仓管理-分页列表查询
	 *
	 * @param orderInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "成品仓管理-分页列表查询")
	@ApiOperation(value="成品仓管理-分页列表查询", notes="成品仓管理-分页列表查询")
	@GetMapping(value = "/glist")
	@PermissionData(pageComponent="cusOrder/CusGoodsInfoList")
	public Result<?> queryGoodsPageList(CusOrderInfo cusOrderInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CusOrderInfo> queryWrapper = QueryGenerator.initQueryWrapper(cusOrderInfo, req.getParameterMap());
		Page<CusOrderInfo> page = new Page<CusOrderInfo>(pageNo, pageSize);
		IPage<CusOrderInfo> pageList = cusOrderInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param orderInfo
	 * @return
	 */
	@AutoLog(value = "订单信息-添加")
	@ApiOperation(value="订单信息-添加", notes="订单信息-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody CusOrderInfo cusOrderInfo) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String codeNum = String.valueOf(FillRuleUtil.executeRule(cusOrderInfo.getCodeNumKey(),null));
		cusOrderInfo.setCodeNum(codeNum);
		cusOrderInfo.setSellBy(loginUser.getUsername());
		cusOrderInfoService.save(cusOrderInfo);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param orderInfo
	 * @return
	 */
	@AutoLog(value = "订单信息-编辑")
	@ApiOperation(value="订单信息-编辑", notes="订单信息-编辑")
	@PutMapping(value = "/edit")
	@Transactional
	public Result<?> edit(@RequestBody CusOrderInfo cusOrderInfo) {
		boolean isSuc = false;
		/**String orderInfoId = cusOrderInfo.getId();
		CusOrderInfo oldOrderInfo = cusOrderInfoService.getById(orderInfoId);
		String remark = oldOrderInfo.getRemark();
		if(remark != null && !"".equals(remark)) {//如果原来订单信息里面的备注不为空
			if(cusOrderInfo.getRemark() != null && !"".equals(cusOrderInfo.getRemark()) && !cusOrderInfo.getRemark().equals(remark)) {//内容有变化
				List<CusStyleInfo> list = this.cusOrderInfoService.getCusStyleInfoListByOrderId(orderInfoId);
				List<CusStyleInfo> updList = new ArrayList<>();
				for(CusStyleInfo cusStyleInfo : list) {
					CusStyleInfo updCusStyleInfo = new CusStyleInfo();
					updCusStyleInfo.setProductionRequirement(cusOrderInfo.getRemark());
					updCusStyleInfo.setId(cusStyleInfo.getId());
					updList.add(updCusStyleInfo);
				}
				isSuc = this.cusStyleInfoService.updateBatchById(updList);
			}
		}*/
		isSuc = cusOrderInfoService.updateById(cusOrderInfo);
		return isSuc ? Result.OK("编辑成功!") : Result.error("编辑失败!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "订单信息-通过id删除")
	@ApiOperation(value="订单信息-通过id删除", notes="订单信息-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		cusOrderInfoService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "订单信息-批量删除")
	@ApiOperation(value="订单信息-批量删除", notes="订单信息-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));
		List<String> removeOrderIds = new ArrayList<>();
		List<String> removeCusStyleIds = new ArrayList<>();
		for(String orderId : idList) {
			CusOrderInfo orderInfo = this.cusOrderInfoService.getById(orderId);
			if(orderInfo.getStatus() < 4) {//未生成工单的订单都可以删除
				removeOrderIds.add(orderId);
				QueryWrapper<CusStyleInfo> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("order_info_id", orderId);
				List<CusStyleInfo> cusStyleList = this.cusStyleInfoService.list(queryWrapper);//订单款式数据集合
				for(CusStyleInfo cusStyle : cusStyleList) {
					removeCusStyleIds.add(cusStyle.getId());//款式ID
				}
			}
		}
		this.cusStyleInfoService.delBatchMain(removeCusStyleIds);//删除订单款式数据
		this.cusOrderInfoService.removeByIds(removeOrderIds);//删除订单数据
		return Result.OK("批量删除成功!");
	}
	
	/**
	 *  批量取消
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "订单信息-批量取消")
	@ApiOperation(value="订单信息-批量取消", notes="订单信息-批量取消")
	@DeleteMapping(value = "/cancelBatch")
	public Result<?> cancelOrder(@RequestParam(name="ids",required=true) String ids,@RequestParam(name="status",required=true) String status) {
		this.cusOrderInfoService.cancelByIds(Arrays.asList(ids.split(",")),status);
		return Result.OK("操作成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "订单信息-通过id查询")
	@ApiOperation(value="订单信息-通过id查询", notes="订单信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		CusOrderInfo cusOrderInfo = cusOrderInfoService.getById(id);
		if(cusOrderInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cusOrderInfo);
	}
	
	/**
	 * 通过订单id查询款式
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "订单信息-通过订单id查询款式")
	@ApiOperation(value="订单信息-通过订单id查询款式", notes="订单信息-通过订单id查询款式")
	@GetMapping(value = "/listStyleInfoByMainId")
	public Result<?> listStyleInfoByMainId(@RequestParam(name = "id",required = false) String id) {
		if(id == null || "".equals(id)) {
			return Result.OK();
		}
		QueryWrapper<CusStyleInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("order_info_id", id);
		queryWrapper.orderByDesc("create_time");
		Page<CusStyleInfo> page = new Page<CusStyleInfo>(1, 10000);
		IPage<CusStyleInfo> pageList = cusStyleInfoService.page(page,queryWrapper);
		List<CusStyleInfo> list = pageList.getRecords();
		if(list == null || list.size() == 0) {
			return Result.error("未找到对应数据");
		}
		for(CusStyleInfo cusStyleInfo : list) {
			Integer styleCate = cusStyleInfo.getStyleCate();
			String karatId = cusStyleInfo.getGoldKaratId();
			Integer isOpen = cusStyleInfo.getIsOpen();
			Integer isConvert = cusStyleInfo.getIsConvert();
			Integer shipmentStatus = cusStyleInfo.getShipmentStatus();
			Integer status = cusStyleInfo.getStatus();
			Integer styleSizeUnit = cusStyleInfo.getStyleSizeUnit();
			cusStyleInfo.setStatusName(sysDictService.queryDictTextByKey("order_status", String.valueOf(status)));
			cusStyleInfo.setShipmentStatusName(sysDictService.queryDictTextByKey("shipment_status", String.valueOf(shipmentStatus)));
			StyleInfo styleInfo = this.styleInfoService.getById(cusStyleInfo.getParentStyleInfoId());
			cusStyleInfo.setCodeNum(styleInfo != null ? styleInfo.getCodeNum() : "");
			cusStyleInfo.setGoldKaratName(this.cusOrderInfoMapper.getGoldKaratName(karatId));
			cusStyleInfo.setStyleCateName(sysDictService.queryDictTextByKey("style_type", String.valueOf(styleCate)));
			cusStyleInfo.setIsOpenName(sysDictService.queryDictTextByKey("yn", String.valueOf(isOpen)));
			cusStyleInfo.setIsConvertName(sysDictService.queryDictTextByKey("yn", String.valueOf(isConvert)));
			cusStyleInfo.setStyleSizeUnitName(sysDictService.queryDictTextByKey("style_size_unit", String.valueOf(styleSizeUnit)));
			String orderInfoId = cusStyleInfo.getOrderInfoId();
			CusOrderInfo cusOrderInfo  = this.cusOrderInfoService.getById(orderInfoId);
			if(cusOrderInfo.getStatus()>=2) {
				cusStyleInfo.setHasExame(true);
			} else {
				cusStyleInfo.setHasExame(false);
			}
		}
		return Result.OK(list);
	}
	
	
	/**
	 *  订单转审核
	 *
	 * @param orderInfo
	 * @return
	 */
	@AutoLog(value = "订单信息-订单转审核")
	@ApiOperation(value="订单信息-订单转审核", notes="订单信息-订单转审核")
	@PostMapping(value = "/passToExamineCusOrder")
	public Result<?> passToExamineCusOrder(@RequestBody CusOrderInfo cusOrderInfo) {
		List<CusStyleInfo> cusStyleInfoList = cusOrderInfoService.getCusStyleInfoListByOrderId(cusOrderInfo.getId());
		for(CusStyleInfo cusStyleInfo : cusStyleInfoList) {
			String goldKaratId = cusStyleInfo.getGoldKaratId();//成色
			Integer count = cusStyleInfo.getCount();//下单数量
			String codeNum = this.styleInfoService.getById(cusStyleInfo.getParentStyleInfoId()).getCodeNum();//款号
			if(goldKaratId == null || "".equals(goldKaratId)) {
				return Result.error("款号："+codeNum+" 成色未设置！");
			}
			if(count == null || count == 0) {
				return Result.error("款号："+codeNum+" 下单数量未设置！");
			}
		}
		
		//String examineBy =cusOrderInfo.getExamineBy();//要将用户名转成id
		//SysUser user = this.sysUserService.getUserByName(examineBy);
		//cusOrderInfo.setExamineBy(user.getId());
		cusOrderInfo.setStatus(1);//将状态设置为：1待审单
		boolean isSuc = cusOrderInfoService.updateById(cusOrderInfo);
		isSuc = cusStyleInfoService.updateStatusByOrderInfoId(cusOrderInfo.getId(), 1);//根据订单号更新所订款式的状态:1待审单
		if(isSuc) {
			try {//发送站内消息提醒
				CusOrderInfo orderInfo = cusOrderInfoService.getById(cusOrderInfo.getId());
				SysUser receiveUser = this.sysUserService.getUserByName(orderInfo.getExamineBy());
				SysAnnouncementController announcementController = (SysAnnouncementController) SpringContextUtils.getBean(SysAnnouncementController.class);
				String title = "审单通知";
				String msgContent = "订单号："+orderInfo.getCodeNum() +"，下单数量："+orderInfo.getCount()+"，请登录系统审核订单。";
				announcementController.addAndSend(title, msgContent, 1, receiveUser.getId()+",");
			} catch (ParseException e) {
				e.printStackTrace();
				isSuc = false;
			}
		}
		return isSuc ? Result.ok("操作成功!") : Result.error("操作失败!");
	}
	
	/**
	 *  订单转审核
	 *
	 * @param orderInfo
	 * @return
	 */
	@AutoLog(value = "订单信息-订单审核")
	@ApiOperation(value="订单信息-订单审核", notes="订单信息-订单审核")
	@PostMapping(value = "/examineCusOrder")
	@Transactional
	public Result<?> examineCusOrder(@RequestBody CusOrderInfo cusOrderInfo) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String sendBy = "";//发送人
		String sendDept = "";//发送部门
		String receiveBy = "";//接收人
		String receiveDept = "";//接收部门
		String storeBy = "";//存货人
		String storeDept = "";//存货部门
		Date nowTime = new Date();//当前时间
		if(!cusOrderInfo.getExamineBy().equals(loginUser.getUsername())) {
			return Result.error("当前用户与该订单的审单人不一致!");
		}
		cusOrderInfo.setStatus(cusOrderInfo.getStatus());//-1审单不通过   2待转生产单（即审单通过）
		cusOrderInfo.setExamineRemark(cusOrderInfo.getExamineRemark());
		cusOrderInfo.setExamineBy(loginUser.getUsername());
		cusOrderInfo.setExamineTime(new Date());
		boolean isSuc = cusOrderInfoService.updateById(cusOrderInfo);
		try {// 发送站内消息提醒
			if (isSuc) {
				CusOrderInfo orderInfo = cusOrderInfoService.getById(cusOrderInfo.getId());
				SysUser receiveUser = this.sysUserService.getUserByName(orderInfo.getSellBy());
				SysAnnouncementController announcementController = (SysAnnouncementController) SpringContextUtils
						.getBean(SysAnnouncementController.class);
				if(receiveUser != null) {
					String title = "审单结果通知";
					String resultMsg = "";// 审核结果信息
					if (orderInfo.getStatus() == 2) {
						resultMsg = "审核通过";
					} else {
						resultMsg = "审核不通过";
					}
					String msgContent = "订单号：" + orderInfo.getCodeNum() + "，下单数量："
							+ orderInfo.getCount() + "，" + resultMsg + "，请登录系统查看详情。";
					announcementController.addAndSend(title, msgContent, 1, receiveUser.getId() + ",");
				}
				// 判断是否由系统自动生产开单
				SysConfig sysConfig = sysConfigService.getOne(null);
				if (sysConfig == null || sysConfig.getIsAutoOpenWorkorder() == null) {
					return Result.error("未找到对应的参数配置");
				} else if(sysConfig.getIsAutoOpenWorkorder() == 1 && sysConfig.getDefaultStoreBy() == null) {
					return Result.error("当前为自动生产开单模式，请设置开单默认存货人！");
				}
				if (sysConfig.getIsAutoOpenWorkorder() == 1) {//审完订单自动生产开单
					SysUser user = this.sysUserService.getUserByName(sysConfig.getDefaultStoreBy());
					sendBy = loginUser.getUsername();//发送人
					sendDept = loginUser.getOrgCode();//发送部门
					receiveBy = user.getUsername();//接收人
					receiveDept = user.getOrgCode();//接收部门
					storeBy = user.getUsername();//存货人
					storeDept = user.getOrgCode();//存货部门
				} else {
					sendBy = loginUser.getUsername();//发送人
					sendDept = loginUser.getOrgCode();//发送部门
					receiveBy = loginUser.getUsername();//接收人
					receiveDept = loginUser.getOrgCode();//接收部门
					storeBy = loginUser.getUsername();//存货人
					storeDept = loginUser.getOrgCode();//存货部门
				}
				
				if (sysConfig.getIsAutoOpenWorkorder() == 1) {//审完订单自动生产开单
					cusOrderInfo.setStatus(4);// 将状态设置为：4待安排做货
					cusOrderInfoService.updateById(cusOrderInfo);
					cusStyleInfoService.updateStatusByOrderInfoId(orderInfo.getId(), 4);//同步更新订单款式的状态
					List<CusStyleInfo> cusStyleInfoList = this.cusOrderInfoService.getCusStyleInfoListByOrderId(cusOrderInfo.getId());
					for (CusStyleInfo cusStyleInfo : cusStyleInfoList) {
						String workNum = String.valueOf(FillRuleUtil.executeRule("work_num_code", null));// 工单号
						WorkingOrder workingOrder = new WorkingOrder();
						workingOrder.setPn("01");// 默认01拆分页
						workingOrder.setWorkNum(workNum);// 工单号
						workingOrder.setStyleCodeNum(cusStyleInfo.getCodeNum());//款号
						workingOrder.setStyleImageString(cusStyleInfo.getStyleImageString());//图片
						workingOrder.setOrderInfoId(orderInfo.getId());// 订单ID
						workingOrder.setStyleCusInfoId(cusStyleInfo.getId());// 款式ID
						workingOrder.setWorkOrderType(1);// 工单类型：1开单单 2拆单单 3移交单 4生产单 5回收单 6出货单 7补单单 8合并单...
						workingOrder.setCount(cusStyleInfo.getCount());// 存货数量
						workingOrder.setStoreBy(storeBy);// 存货人
						workingOrder.setStoreDept(storeDept);// 存货部门
						workingOrder.setStoreStatus(1);// 存货状态：1存货、2报废、3交货
						workingOrder.setOpenWorkorderDate(nowTime);//开单日期
						workingOrder.setDeliveryDate(cusStyleInfo.getDeliveryDate());//交货日期
						workingOrder.setPid("0");// 根节点
						isSuc = workingOrderService.save(workingOrder);// 保存生产开工单数据
						isSuc = cusStyleInfoService.openWorkOrder(cusStyleInfo.getId());// 设置订单的开工单状态
							
						if(receiveBy != null && !"".equals(receiveBy)) {//当设置了移交接收人的时候，需要发送站内通知，提醒接收人
							WorkingOrderRecord workingOrderRecord = new WorkingOrderRecord();
							workingOrderRecord.setCount(cusStyleInfo.getCount());//数量
							workingOrderRecord.setParentId("0");//默认是根节点
							workingOrderRecord.setWorkOrderType(1);//工单类型：1开单单 2拆单单 3移交单 4生产单 5回收单 6出货单 7补单单 8合并单...
							workingOrderRecord.setPn("01");// 默认01拆分页
							workingOrderRecord.setWorkNum(workNum);//工单号
							workingOrderRecord.setStoreStatus(1);//存货状态：1存货、2报废、3交货
							workingOrderRecord.setSendBy(sendBy);// 发送人
							workingOrderRecord.setSendDept(sendDept);// 发送部门
							workingOrderRecord.setSendTime(nowTime);// 发送时间
							workingOrderRecord.setReceiveBy(receiveBy);// 接收人
							workingOrderRecord.setReceiveDept(receiveDept);// 接收部门
							workingOrderRecord.setReceiveTime(nowTime);// 接收时间
							workingOrderRecord.setWorkingOrderId(workingOrder.getId());// 工单ID
							workingOrderRecordService.addWorkingOrderRecord(workingOrderRecord);// 写入数据库，保存数据
							WorkingOrder updateWorkingOrder = new WorkingOrder();
							updateWorkingOrder.setCurrWorkingOrderRecordId(workingOrderRecord.getId());
							updateWorkingOrder.setId(workingOrder.getId());
							workingOrderService.updateById(updateWorkingOrder);// 写入数据库，保存数据
							try {//发送站内消息提醒
								SysUser receiveUser2 = sysUserService.getUserByName(receiveBy);
								String title = "生产开单通知"+"(工单号："+workNum +")";
								String msgContent = "工单号："+workNum +"，数量："+workingOrder.getCount()+"，请安排生产计划。详情登录查看生产跟单系统。";
								announcementController.addAndSend(title, msgContent, 1, receiveUser2.getId()+",");
							} catch (ParseException e) {
								e.printStackTrace();
								isSuc = false;
							}
						}
					}
					if(!cusStyleInfoList.isEmpty()) {
						SysUser receiveUser3 = sysUserService.getUserByName(receiveBy);
						String title = "生产开单通知"+"(订单号：" + orderInfo.getCodeNum()+")";
						String msgContent = "订单号：" + orderInfo.getCodeNum() + "，客户：" + orderInfo.getCustomerInfoId() + "，下单数量："
								+ orderInfo.getCount() + "，生产工单已开，请情登录系统查看并安排生产。";
						announcementController.addAndSend(title, msgContent, 1, receiveUser3.getId() + ",");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			isSuc = false;
		}
		return isSuc ? Result.ok("订单审核成功!") : Result.error("订单审核失败！");
	}
	
	/**
	 *  转生产单
	 *
	 * @param orderInfo
	 * @return
	 */
	@AutoLog(value = "订单信息-转生产单")
	@ApiOperation(value="订单信息-转生产单", notes="订单信息-转生产单")
	@PostMapping(value = "/toConvertProdOrder")
	public Result<?> toConvertProdOrder(@RequestBody CusOrderInfo cusOrderInfo) {
		cusOrderInfo.setStatus(3);//将状态设置为：3待转生产单
		cusOrderInfoService.updateById(cusOrderInfo);
		return Result.OK("操作成功!");
	}
	
	/**
	 *   通过id检查是否已选款
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "订单信息-通过id检查是否已选款")
	@ApiOperation(value="订单信息-通过id检查是否已选款", notes="订单信息-通过id检查是否已选款")
	@GetMapping(value = "/checkOrderStyle")
	public Result<?> checkOrderStyle(@RequestParam(name="orderInfoId",required=true) String orderInfoId) {
		boolean checkResult = cusOrderInfoService.checkOrderStyle(orderInfoId);
		return checkResult ? Result.OK(checkResult) : Result.error("该订单尚未选款，暂不能提交审核！", checkResult);
	}


    /**
	 *   一键转生产单
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "款式资料-一键转生产单")
	@ApiOperation(value="款式资料-一键转生产单", notes="款式资料-一键转生产单")
	@GetMapping(value = "/convertProdOrder")
	public Result<?> convertProdOrder(@RequestParam(name="id",required=true) String id) {
		List<CusStyleInfo> cusStyleInfoList = cusOrderInfoService.getCusStyleInfoListByOrderId(id);
		boolean isSuc = false;
		if(!cusStyleInfoList.isEmpty()) {
			for(CusStyleInfo cusStyleInfo : cusStyleInfoList) {
				if(cusStyleInfo.getIsConvert() == 0) {//未转生产单的才需要转
					if(cusStyleInfo.getCount() == 0) {
						return Result.error("该款式的下单数量未录入，请设置!");
					} else if(cusStyleInfo.getGoldKaratId() == null || "".equals(cusStyleInfo.getGoldKaratId())) {
						return Result.error("该款式的成色未选定，请设置!");
					}
					isSuc = cusStyleInfoService.convertProdOrder(cusStyleInfo.getId());
				}
			}
			if(isSuc) {
				CusOrderInfo cusOrderInfo = cusOrderInfoService.getById(id);
				if(cusOrderInfo.getStatus() == 2) {//订单仍是待转生产单状态。0暂存草稿 1待审单 -1审单不通过 2待转生产单 3待开工单 4已开工单 5完成工单
					int allOrderStyleCount = cusOrderInfoMapper.countAllOrderStyle(id);
					int convertedStyleCount = cusOrderInfoMapper.countConvertedOrderStyle(id);
					if(convertedStyleCount == allOrderStyleCount) {
						//如果该订单下的款式都已转生产单，则更新订单状态为：3待开工单
						cusOrderInfoService.updateStatus(id, 3);
					}
				}
			}
		}
		return isSuc ? Result.OK("转生产单成功!") : Result.error("转生产单失败!",isSuc) ;
	}
	
	/**
	 *  成品仓管理-出货
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "成品仓管理-出货")
	@ApiOperation(value="成品仓管理-出货", notes="成品仓管理-出货")
	@PostMapping(value = "/shipment")
	@Transactional
	public Result<?> shipment(@RequestBody JSONObject params) {
		String cusStyleInfoId = params.getString("cusStyleInfoId");
		CusStyleInfo cusStyleInfo = this.cusStyleInfoService.getById(cusStyleInfoId);
		if(cusStyleInfo == null) {
			return Result.error("未找到对应数据");
		}
		Integer count = cusStyleInfo.getCount();//下单数量
		Integer doCount = cusStyleInfo.getDoCount();//做货数量
		Integer shipmentCount = params.getInteger("shipmentCount");//出货数量
		Integer noShipmentCount = doCount - shipmentCount;//未出货数量
		if(count <= 0) {
			Result.error("下单数量为0，暂时不能出货！");
		}
		if(doCount <= 0) {
			Result.error("做货数量为0，暂时不能出货！");
		}
		if(shipmentCount > doCount) {
			Result.error("出货数量不能超过做货数量("+doCount+")！");
		}
		boolean isSuc = false;
		
		/**更新订单款式的出货信息*/
		UpdateWrapper<CusStyleInfo> updateCusStyleInfo = new UpdateWrapper<>();
		updateCusStyleInfo.eq("id", cusStyleInfoId);
		updateCusStyleInfo.set("shipment_count", shipmentCount);//出货数量
		updateCusStyleInfo.set("no_shipment_count", noShipmentCount);//未出货数量
		updateCusStyleInfo.set("shipment_status", noShipmentCount > 0 ? 20 :21);//出货状态：0待出货、20部分出货、21全部出货
		isSuc = this.cusStyleInfoService.update(updateCusStyleInfo);

		/**更新订单的出货信息*/
		UpdateWrapper<CusOrderInfo> updateOrderInfo = new UpdateWrapper<>();
		CusOrderInfo oldCusOrderInfo = this.cusOrderInfoService.getById(cusStyleInfo.getOrderInfoId());
		Integer oldShipmentCount = oldCusOrderInfo.getShipmentCount();//原：出货数量
		Integer newShipmentCount = oldShipmentCount + shipmentCount;//新：出货数量
		Integer newNoShipmentCount = noShipmentCount - shipmentCount;//新：未出货数量
		
		updateOrderInfo.eq("id", cusStyleInfo.getOrderInfoId());
		updateOrderInfo.set("shipment_count", newShipmentCount);
		updateOrderInfo.set("no_shipment_count", newNoShipmentCount);
		updateOrderInfo.set("shipment_status", newNoShipmentCount > 0 ? 20 :21);//出货状态：0待出货、20部分出货、21全部出货
		isSuc = this.cusOrderInfoService.update(updateOrderInfo);
		if(!isSuc) {
			throw new RuntimeException("出货失败！");
		}
		return  Result.ok("成功出货"+shipmentCount+"件！");
	}
	
    /**
    * 导出excel
    *
    * @param request
    * @param orderInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CusOrderInfo cusOrderInfo) {
        return super.exportXls(request, cusOrderInfo, CusOrderInfo.class, "订单信息");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CusOrderInfo.class);
    }
    
    

}
